import { createItem, fetchItems, updateItem } from '@/redux/user/user-actions';
import { IRootReducerState } from '@/store/root-reducer';
import { Button, Modal } from '@douyinfe/semi-ui';
import { useEffect, useMemo, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { useParams } from 'react-router-dom';
import { usePageContext } from '../context';
import UserDetail from './detail';
import UserEdit from './edit';
import * as actions from '../../../../redux/user/user-actions';
import { assignRole } from '@/redux/user/user-api';

const UserEntityDialog = ({ open, onClose, editable = true }: any) => {
  const { id } = useParams();
  const dispatch = useDispatch();
  const PageContext = usePageContext();
  const [title, setTitle] = useState('');

  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
    };
  }, [PageContext]);

  const { user } = useSelector<IRootReducerState, any>(
    (state) => ({ user: state.user }),
    shallowEqual
  );
  const { entities, totalCount, actionsLoading } = user;

  // Title couting
  useEffect(() => {
    let _title = id ? '' : '新建用户';
    if (id) {
      _title = `编辑用户`;
    }

    setTitle(_title);
    // eslint-disable-next-line
  }, [id, actionsLoading]);

  const entityForEdit = useMemo(() => {
    if (id) {
      const _entity = {
        ...entities?.filter(
          (rule: any) => rule.id.toString() === id.toString()
        )[0],
      };

      return _entity;
    }
    return null;
  }, [entities, id]);

  const persistEntity = (entity: any) => {
    console.log('点击保存--->', entity);
    if (!id) {
      // @ts-ignore
      dispatch(actions.createItem(entity)).then(() => {
        onClose();
        // @ts-ignore
        dispatch(actions.fetchItems(PageAction.queryParams)).then(
          (res: any) => {
            console.log(res);
          }
        );
      });
    } else {
      if (entity?.roleIdList) {
        assignRole({ userId: entity?.userId, roleIdList: entity?.roleIdList });
      }
      // @ts-ignore
      dispatch(actions.updateItem(entity)).then(() => {
        onClose();
        // @ts-ignore
        dispatch(actions.fetchItems(PageAction.queryParams)).then(
          (res: any) => {
            console.log(res);
          }
        );
      });
    }
  };

  return (
    <Modal
      title={title}
      size='medium'
      visible={open}
      // onOk={handleOk}
      footer={null}
      onCancel={onClose}
    >
      {editable ? (
        <>
          <UserEdit entity={entityForEdit} persistEntity={persistEntity} />
        </>
      ) : (
        <UserEdit entity={entityForEdit} />
      )}
    </Modal>
  );
};

export default UserEntityDialog;
